<?php

function urlToLink($str) {
    $arr = array("www." => "http://www.");
    $str = strtr($str, $arr);
    $arr = array("http://http://" => "http://");
    $str = strtr($str, $arr);
    $str2 = explode("http://", $str);
    $url = '';
    for ($n = 1; isset($str2[$n]); $n ++) {
        $str3 = explode(".", $str2[$n]);
        if (isset($str3[1])) {
            $str4 = explode("www.", $str2[$n]);
            if ((isset($str4[1]) && isset($str3[2])) || !isset($str4[1])) {
                $length = strlen($str2[$n]);
                for ($i = 0; $i <= $length; $i ++) {
                    //从空格断开
                    if (($i - 1) == strlen(trim(mb_substr($str2[$n], 0, $i, 'gb2312')))) {
                        $ii = $i - 1;
                        $url1 = mb_substr($str2[$n], 0, $ii, 'gb2312');
                        $url2 = mb_substr($str2[$n], $ii, $length, 'gb2312');
                        $url3 = "<a href=\"http://" . $url1 . "\" target=\"_blank\">http://" . $url1 . "</a>" . $url2;
                        break;
                    }

                    //从出现汉字处断开
                    if ($i != strlen(mb_substr($str2[$n], 0, $i, 'gb2312'))) {
                        $ii = $i - 1;
                        $url1 = mb_substr($str2[$n], 0, $ii, 'gb2312');
                        $url2 = mb_substr($str2[$n], $ii, $length, 'gb2312');
                        $url3 = "<a href=\"http://" . $url1 . "\" target=\"_blank\">http://" . $url1 . "</a>" . $url2;
                        break;
                    }
                    if ($i == $length)
                        $url3 = "<a href=\"http://" . $str2[$n] . "\" target=\"_blank\">http://" . $str2[$n] . "</a>";
                }
            } else
                $url3 = "http://" . $str2[$n];
        } else
            $url3 = "http://" . $str2[$n];
        $url .= $url3;
    }
    if (substr($str, 0, 7) == "http://")
        $url = "<a href=\"http://$str2[0]\" target=\"_blank\">" . $str2[0] . "</a>" . $url;
    else
        $url = $str2[0] . $url;
    return $url;
}

//邀请码
function get_invite_code() {
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0, 25)] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
    for ($a = md5($rand, true), $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV', $d = '', $f = 0; $f < 5; $g = ord($a[$f]), $d .= $s[( $g ^ ord($a[$f + 5]) ) - $g & 0x1F], $f++)
        ;
    return strtolower($d);
}

function getCommentContent($content) {

    $content = stripslashes($content);
    $content = str_replace("[code]", "<pre><code class='html'>", $content);
    $content = str_replace("[code='html']", "<pre><code class='html'>", $content);
    $content = str_replace("[code='js']", "<pre><code class='js'>", $content);
    $content = str_replace("[code='css']", "<pre><code class='css'>", $content);
    $content = str_replace("[code='php']", "<pre><code class='php'>", $content);
    $content = str_replace("[/code]", "</code></pre>", $content);
    $tagsArr = array("code", "pre", "em", "b", "strong", "p", "br", "a", "span", "dd", "dl", "dt", "table", "tr", "th", "td", "thead", "tbody", "img",
        "h1", "h2", "h3", "h4", "h5", "h5", "div", "i", "dfn", "u", "ins", "strike", "s", "del", "font", "hr", "center", "caption", "html", "body", "ul", "li", "ol", "select", "small", "input", "textarea"
    );
    $tags = "";
    foreach ($tagsArr as $v) {
        $tags .="<" . $v . ">";
    }
    return strip_tags($content, $tags);
}

function getUrlJson($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 获取数据返回  
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回  
    return $output = curl_exec($ch);
}

function getHighlight($keywords, $keyword) {
    if ($keyword) {
        $keywords = preg_replace("/($keyword)/i", "<b style=\"color:red\">\\1</b>", $keywords);
    }
    return $keywords;
}

function getHtmlCacheRule($paras) {
    $parasArr = explode(",", $paras);
    $id = $parasArr[0];
    $para = $parasArr[1];
    $mtype = $parasArr[2];
    if ($id > 0) {
        $html = $mtype . "/" . getFileBei($id) . $id;
    } else if ($id == '' && $para == '') {
        $html = $mtype . "/index";
    } else {

        $html = $mtype . "/paras/" . $para;
    }
    return $html;
}

function codeAuto($data, $output = 'utf-8') {
    $encode_arr = array('UTF-8', 'ASCII', 'GBK', 'GB2312', 'BIG5', 'JIS', 'eucjp-win', 'sjis-win', 'EUC-JP');
    $encoded = mb_detect_encoding($data, $encode_arr); //自动判断编码

    if (!is_array($data)) {
        return mb_convert_encoding($data, $output, $encoded);
    } else {
        foreach ($data as $key => $val) {
            if (is_array($val)) {
                $data[$key] = array_iconv($val, $input, $output);
            } else {
                $data[$key] = mb_convert_encoding($data, $output, $encoded);
            }
        }
        return $data;
    }
}

function getGb2312($file) {
    return iconv('UTF-8', 'GB2312', $file);
}

function getUtf8($file) {
    return iconv('GB2312', 'UTF-8', $file);
}

function is_Gb2312($file) {
    $host_ip = $_SERVER["REMOTE_ADDR"]; //222.71.198.188
    if ($host_ip == '127.0.0.1' or $host_ip == '::1') {
        $file = getGb2312($file);
    }
    return $file;
}

function is_Utf8_service($file) {
    if ($_SERVER['HTTP_HOST'] != 'localhost') {
        $file = getUtf8($file);
    }
    return $file;
}

function getFileBei($id) {
    return intval($id / 100) . "/";
}

function getEqual($a, $b, $rs, $fuhao = 'eq') {
    if ($fuhao > 0) {
        if ($a % $fuhao == $b) {
            return $rs;
        }
    } else {
        if ($fuhao == 'eq') {
            if ($a == $b) {
                return $rs;
            }
        } elseif ($fuhao == 'gt') {
            if ($a > $b) {
                return $rs;
            }
        } elseif ($fuhao == 'in') {
            $arr = explode(",", $b);
            if (in_array($a, $arr)) {
                return $rs;
            }
        } elseif ($fuhao == 'not_null') {
            if ($a != '') {
                return $rs;
            }
        }
    }
}

function getStar($star) {
    $span = "<span class='c-value-no c-value-4d" . intval($star) . "'><em></em></span>";
    return $span;
}

function getChecked($ids, $id) {
    if (!empty($ids)) {
        $ids = explode(",", $ids);
        if (in_array($id, $ids)) {
            return "checked";
        }
    }
}

function getSingleField($id, $table, $field, $word) {
    if (!empty($id)) {
        $ids = explode(",", $id);
        if (count($ids) >= 2) {
            $info = M($table)->field($field)->where("id in (" . $id . ")")->find();
        } else {
            $info = M($table)->field($field)->where("id = " . $id . "")->find();
        }
        if ($info[$field] != '') {
            return $info[$field];
        } else {
            return $word;
        }
    }
}

//截取字符串
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) {
    if (function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif (function_exists('iconv_substr')) {
        $slice = iconv_substr($str, $start, $length, $charset);
        if (false === $slice) {
            $slice = '';
        }
    } else {
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("", array_slice($match[0], $start, $length));
    }
    $fix = '';
    if (strlen($slice) < strlen($str)) {
        $fix = '...';
    }
    return $suffix ? $slice . $fix : $slice;
}

function get_extension($file) {
    $fileArr = explode("?", $file);
    $type = strtolower(substr(strrchr($fileArr[0], '.'), 1));
    return $type;
}

function getFilePrev($name) {
    $arr = explode(".", $name);
    return $arr[0];
}

function getThreeField($three, $big, $small) {
    $detail = json_decode($three[$big], true);
    return $detail[$small];
}

function getTableFile($table) {
    $commonTable = array("accounts", "friends");
    $ordTable = array("dictionary", "modals_tags");
    if (in_array($table, $commonTable)) {
        $ord = "ord ASC";
        $where = "is_check=1";
    } elseif (in_array($table, $ordTable)) {
        $ord = "ord ASC,id DESC";
    }
    $lists = F('' . $table . '/data');
    if (empty($lists)) {
        $lists = M($table)->where($where)->order($ord)->select();

        F('' . $table . '/data', $lists);
    }
    return $lists;
}

function getTableConfig() {
    $config = F('config/data');
    if (empty($config)) {
        $config = M("config")->where("id = 1")->find();
        F('config/data', $config);
    }
    return $config;
}

function addCommentContent($content) {
    return str_replace("\r\n", "<br />", $content);
}

function getUserId() {
    $userid = session("userid");
    if (!$userid) {
        $c_checkcode = getSessionCookie("unionCheckcode");
        if ($c_checkcode) {
            $userid = cookie('userid');
            if ($c_checkcode == getUnionLoginCheckcode($userid)) {
                $info = M("user")->field("name")->where("id= '" . $userid . "'")->find();
                if (!empty($info['name'])) {
                    session('username', $info['name']);
                    session('userid', $userid);
                }
            }
        } else {
            emptySessionCookie('userid');
            session('username', null);
            session('admin_uid', null);
            session('admin_name', null);
        }
    } else {
        $c_checkcode = getSessionCookie("unionCheckcode");

        if ($c_checkcode != getUnionLoginCheckcode($userid) || $c_checkcode == '') {
            $userid = "";
        }
    }
    return $userid;
}

function getUnionLoginCheckcode($uid) {
    $privateKey = C("privateKey");
    return md5(Sha1(md5(md5($uid . $privateKey))) . "_ABC*");
}

function getError($msg, $code) {
    echo json_encode(array("error" => $msg, "code" => $code));
}

function setSessionCookie($k, $v) {
    session($k, $v,3600000);
    cookie($k, $v,3600000);
}

function getSessionCookie($k) {
    $s_k = session($k);
    $rs = $s_k ? $s_k : cookie($k);
    return $rs;
}

function emptySessionCookie($k) {
    session($k, null);
    cookie($k, null);
}

function replace_specialChar($strParam) {
    $regex = "/\/|\~|\!|\@|\#|\\$|\%|\、|\^|\&|\*|\(|\)|\_|\{|\}|\:|\<|\>|\?|\[|\]|\,|\/|\;|\'|\`|\-|\=|\\\|\|/";
    return preg_replace($regex, "", $strParam);
}

function getDictionarySubSql($code, $table = 'dictionary_modals') {
    $pids = M($table)->field("id")->where("code = '" . $code . "'")->find();
    $lists = M($table)->field("id,name")->where("pid = '" . $pids['id'] . "'")->order("ord ASC")->select();
//    echo M($table)->getlastsql();
    return $lists;
}

function getZipFileLists($zip_url) { //列出压缩文件列表 
    import("Common.Org.PclZip");
    $zip = new PclZip($zip_url);
    $lists = $zip->listContent();
    return $lists;
//    if (($list = $zip->listContent()) == 0) { 
//        die("Error : " . $zip->errorInfo(true)); 
//    } 
//    $files = array();
//    for ($i = 0; $i < sizeof($list); $i++) { 
//        for (reset($list[$i]); $key = key($list[$i]); next($list[$i])) { 
//            $files[$i][$key][] = $list[$i][$key];
////            echo "File " . $i . " / [" . $key . "] = " . $list[$i][$key] . "<br />"; 
//        } 
//     return $files;
//    } 
}

function getMiddleLogo($logo) {
    $height = 0;
//        echo $logo;exit;
    if (file_exists($logo)) {
        $fileArr = pathinfo($logo);
        $dirname = $fileArr['dirname'];
        $extension = $fileArr['extension'];
        $image_info = getimagesize($logo);
          $width = 268;
        if($dirname =='services'){
            $width = 200;
        }

        $width_real = $image_info[0];
        $height_real = $image_info[1];
        if ($width_real > 0 && $height_real > 0) {
            $height = $width * ($height_real / $width_real);
            if($dirname =='services'){
            $height = 200;
        }
            $name_thumb = $dirname . "/" . "middle" . "." . $extension;
//            echo $name_thumb;exit;
            if (file_exists($logo)) {
                $image = new \Think\Image();
                $image->open($logo);
                $image->thumb($width, $height)->save($name_thumb);


                $height = $height > $height_real ? $height_real : $height;
            } else {
                $height = 0;
            }
        }
    }
    return $height;
}

function getMiddleLogoHeight($logo) {
    $height = 0;
    if (file_exists($logo)) {
        $fileArr = pathinfo($logo);
        $dirname = $fileArr['dirname'];
        $extension = $fileArr['extension'];
        $name_thumb = $dirname . "/" . "middle" . "." . $extension;
        if (file_exists($name_thumb)) {
            $image_info = getimagesize($name_thumb);
            $height = $image_info[1];
        }
    }
    return $height;
}

function getVipEndtime($viptime) {
    $rs = 0;
    if ($viptime > 0) {
        $rs = ceil(($viptime - time()) / 3600 / 24);
    }
    return $rs;
}

function getUserVip($uid) {
    $rs = 0;
    if ($uid > 0) {
        $userinfo = M("user")->field("vip_time")->where("id = " . $uid . "")->find();
        $viptime = $userinfo['vip_time'];

        if ($viptime > time()) {
            $rs = ceil(($viptime - time()) / 3600 / 24);
        }
    }
    return $rs;
}

//防止xss攻击
function halfToFull($str) {
    $filter = array(
        "<" => "＜",
        ">" => "＞",
    );
    foreach ($filter as $key => $val) {
        $str = str_replace($key, $val, $str);
    }
    return $str;
}

function getIP() {
    if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
        $cip = $_SERVER["HTTP_CLIENT_IP"];
    } elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
        $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    } elseif (!empty($_SERVER["REMOTE_ADDR"])) {
        $cip = $_SERVER["REMOTE_ADDR"];
    } else {
        $cip = "无法获取！";
    }
    return $cip;
}

function getJsonExit($code, $result, $info) {
    if ($info) {
        $info['code'] = $code;
        $info['result'] = $result;
    } else {
        $info = array("code" => $code, "result" => $result);
    }
    echo json_encode($info);
    exit;
}

// $email_name = 'admin@mfroad.com'; //zhengzaoxia@yaxzb.com,admin@mfroad.com
//    $email_pwd = '1234!QAZ2wsx'; //ZX200711zx,1234！QAZ2wsx
//    $host = 'smtp.exmail.qq.com';
function sendEmail($code, $to_email, $paras) {
    $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
    if (!preg_match($pattern, $to_email)) {
        return array("code" => "email_error", "result" => "邮箱格式有误");
    }

    $subject = $paras['title'];

    $body = htmlspecialchars_decode($paras['content']);
    $uid = $paras['uid'];
//    $rand = rand(1,10);

    $email_name = "sucaihuo_00" . rand(1, 9) . "@sucaihuo.com"; //zhengzaoxia@yaxzb.com,admin@mfroad.com
    $email_pwd = 'Sucaihuo778899'; //Sucaihuo7233163,1234！QAZ2wsx
    $host = 'smtp.exmail.qq.com'; //smtp.qq.com
    $title = "素材火";
    vendor('phpmailer.class#phpmailer');
    $mail = new PHPMailer(); //PHPMailer对象
    $mail->CharSet = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();  // 设定使用SMTP服务
    $mail->SMTPDebug = 0;                     // 关闭SMTP调试功能
    $mail->SMTPAuth = true;                  // 启用 SMTP 验证功能
    $mail->SMTPSecure = '';                 // 使用安全协议
    $mail->Host = $host;  // SMTP 服务器
    $mail->Port = "";  // SMTP服务器的端口号
    $mail->Username = $email_name;  // SMTP服务器用户名
    $mail->Password = $email_pwd;  // SMTP服务器密码
    $mail->Subject = $subject; //邮件标题
    $mail->SetFrom($email_name, $title);
    $mail->MsgHTML($body);
    $mail->AddAddress($to_email, $title);
    $result = $mail->Send() ? 'ok' : $mail->ErrorInfo;
//    print_r($result);
    addEmailRecord($uid, $code, $subject, $body, $to_email, $result, $email_name);

    $rs = array("code" => "0", "result" => $result,"email_from"=>$email_name);
    return $rs;
}

function addEmailRecord($uid, $code, $title, $content, $accounts, $error, $email_from) {
    $data['code'] = $code;
    $data['title'] = $title;
    $data['content'] = $content;
    $data['accounts'] = $accounts;
    $data['uid'] = intval($uid);
    $data['email_from'] = $email_from;
    $data['error'] = $error;
    M("email_record")->add($data);
}

function curlGet($url) {
    $ch = curl_init();
    $headers[] = 'Accept-Charset:utf-8';
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function curlGetArray($url) {
    $ch = curl_init();
    $headers[] = 'Accept-Charset:utf-8';
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    return json_decode($result,true);
}

function curlPost($url, $data) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

function getParamValues($arr, $fields) {
    $rs = array();
    $fieldsArr = explode(",", $fields);
    foreach ($arr as $k => $v) {
        if (in_array($k, $fieldsArr)) {
            $rs[$k] = trim($v);
        }
    }
    return $rs;
}

function getWeixinPrivateKey($id) {
    $privateKey = C("privateKey");
    return md5(Sha1(md5(md5($id . $privateKey))) . "_ABC*weixin");
}

function getWeixinPrivateHash($password, $salt) {
    return hash("sha256", $password . $salt);
}

function checkDirExists($dir) {
    if (!is_dir($dir)) {
        mkdir($dir, 0777, true);
    }
}

function getUserArea($area) {
    if ($area) {
        $arr = explode(",", $area);
        $areas = array();
        foreach ($arr as $v) {
            if ($v != 'null') {
                $areas[] = $v;
            }
        }
    }
    return implode(",", $areas);
}

function getUserSex($sex) {
    $rs = '保密';
    if ($sex == 1) {
        $rs = '男';
    } elseif ($sex == 2) {
        $rs = '女';
    }
    return $rs;
}
function getUserRegTime($time){
    $rs = '2015-10-01';
    if($time>0){
      $rs=  date("Y-m-d",$time);
    }
    return $rs;
    
}
//判断是否处理
function report_is_handle($is_handle){
    if($is_handle == 1){
        $str = "<span style='color: #00b33b'>已处理</span>";
    }else{
        $str = "<span style='color: #ee1e2d'>未处理</span>";
    }
    return $str;
}

